package com.example.guesswho.data.local

import androidx.room.Entity
import androidx.room.PrimaryKey
import androidx.room.TypeConverter
import androidx.room.TypeConverters
import java.util.Date

@Entity(tableName = "questions")
@TypeConverters(QuestionConverters::class)
data class QuestionEntity(
    @PrimaryKey
    val objectId: String,
    val title: String,
    val coverUrl: String,
    val voiceUrl: String?,
    val options: List<String>,
    val answerIndex: Int,
    val category: String,
    val difficulty: Int,
    val isAudited: Boolean,
    val lastSyncedAt: Date = Date()
)

@Entity(tableName = "rooms")
@TypeConverters(RoomConverters::class)
data class RoomEntity(
    @PrimaryKey
    val objectId: String,
    val difficulty: Int,
    val status: String,   // waiting|playing|ended
    val userIds: List<String>,
    val unansweredCount: Int,
    val createdAt: Date,
    val lastSyncedAt: Date = Date()
)

@Entity(tableName = "audience_chats")
data class AudienceChatEntity(
    @PrimaryKey(autoGenerate = true)
    val id: Long = 0,
    val objectId: String,
    val roomId: String,
    val username: String,
    val text: String,
    val ts: Long
)

@Entity(tableName = "short_links")
data class ShortLinkEntity(
    @PrimaryKey
    val code: String,  // 4位
    val roomId: String,
    val createdAt: Date = Date()
)

// Type converters for QuestionEntity
class QuestionConverters {
    @TypeConverter
    fun fromStringList(value: List<String>): String {
        return value.joinToString(",")
    }
    
    @TypeConverter
    fun toStringList(value: String): List<String> {
        return if (value.isEmpty()) emptyList() else value.split(",")
    }
}

// Type converters for RoomEntity
class RoomConverters {
    @TypeConverter
    fun fromStringList(value: List<String>): String {
        return value.joinToString(",")
    }
    
    @TypeConverter
    fun toStringList(value: String): List<String> {
        return if (value.isEmpty()) emptyList() else value.split(",")
    }
    
    @TypeConverter
    fun fromDate(date: Date): Long {
        return date.time
    }
    
    @TypeConverter
    fun toDate(timestamp: Long): Date {
        return Date(timestamp)
    }
}